/**
 * 网格类: 要求从控制器中获得json格式的数据
 * 
 * 必备配置项
 * 
 * @config {String} gridId 网格对应的div标识
 * @config {String} entityName 网格数据所对应的Entity类名字
 * 
 * 可选配置项 *
 * @config {bool} hasBbar 是否显示状态条（默认为true，表示显示状态条）
 * @config {int} pageSize 分页长度（默认20）
 * @config {bool} showTopToolbar 是否显示顶部的工具条（默认为false，表示不显示）
 * @config {Object} expander 网格的Meta附加控件,比如复选框或自动编号等(默认为null)
 * @config {String} jsonId json数据中的id字段名（默认为'id')
 * @config {bool} checkboxSelectionModel(默认为false,表示不用此模式)
 * @config {String} metaUrl 取网格元数据的请求地址(默认为'get_system_gridmeta.htm')
 * @config {String} queryUrl 获取Grid数据的URL地址
 * @config {String} deleteUrl 删除Grid数据的URL地址
 * @config {String[]} specialFields 指定显示的字段，默认为空
 * @config {bool} remoteSort 是否在服务端排序
 * @config {Map} 存储要键/值对应的列表  Map map=new Map(); Map map1=new Map();map1.put("1","1");map.put("dd",map1);
 */
/*
 * Ext.namespace('Divo'); Ext.namespace('Divo.Base');
 */
Ext.define('gridView', {
	extend : 'Ext.grid.Panel',
	gridId : 'base-grid',
	jsonId : 'id',
	region : 'center',
	pageSize : 20,
	hasBbar : true,
	expander : null,
	remoteSort : false,
	dataAutoLoad : true,// 是否自动加载数据
	checkboxSelectionModel : false,
	entityName : '',
	packageName : '',
	entityClassName : '',
	metaUrl : '../commonController/get_grid_meta.action',
	queryUrl : '',
	deleteUrl : '',
	recordPk : new Array(),
	searchFlds : new Ext.util.MixedCollection(),
	recDef : null,
	colModel : null,
	specialFields : [],
	codeMap : null,
	initComponent : function() {
		if (this.queryUrl == null || this.queryUrl == '') {
			this.queryUrl = this.entityName + '/query';
		}
		var metaData = null;
		// 获取对应的列名，和数据模式
		Ext.Ajax.request({
					url : this.metaUrl,
					scope : this,
					async : false,
					params : {
						entityName : this.entityName,
						packageName : this.packageName,
						entityClassName : this.entityClassName
					},
					callback : function(o, s, r) {
						var resp = Ext.decode(r.responseText);
						if (resp.success) {
							metaData = resp.data;
						}
					}
				});

		if (metaData != null) {
			var sm;
			// 选择模式
			if (this.checkboxSelectionModel) {
				sm = new Ext.selection.CheckboxModel();
			} else {
				sm = new Ext.selection.RowModel();
			}

			this.getBaseGridMeta(metaData);
			var store = this.getDataStore();

			var bbar;
			if (this.bbar) {
				bbar = this.bbar;
			} else {
				if (this.hasBbar) {
					bbar = new Ext.PagingToolbar({
								pageSize : this.pageSize,
								store : store,
								displayInfo : true,
								displayMsg : '显示: {0} - {1} 共 {2} 条',
								emptyMsg : "没有数据"
							});
				} else {
					bbar = null;
				}
			}

			this.id = 'grid' + this.gridId;
			this.store = store;
			this.stateful = true;
			// 收缩/展开按钮
			this.collapsible = false;
			this.multiSelect = true;
			this.stateId = 'stateGrid';
			this.columns = this.colModel;
			this.selModel = sm;
			// this.title = 'Array Grid';
			this.bbar = bbar;
			this.renderTo = Ext.getBody();
			this.viewConfig = {
				stripeRows : true,
				enableTextSelection : true
			};
			// 调用父类方法
			this.callParent(arguments);
			if (this.dataAutoLoad)
				this.load();
		}
	},
	getBaseGridMeta : function(result) {
		var resultLength = result.length;
		if (resultLength == 0) {
			Ext.define('MyData' + this.gridId, {
						extend : 'Ext.data.Model',
						fields : this.recDef,
						idProperty : this.jsonId || 'id'
					});
			this.colModel = cms;
		} else {
			var rs = [], cms = [];
			if (this.expander) {
				cms.push(this.expander);
			}
			for (var i = 0; i < resultLength; i++) {
				switch (result[i].type) {
					case "code" :
						var codeData = null;
						// 获取对应的列名，和数据模式
						if(result[i].attributes!=null && result[i].attributes!=""){
						Ext.Ajax.request({
									url : "../commonController/getCodeData.action",
									scope : this,
									async : false,
									params : {
										type : "code",
										codeName : result[i].attributes
									},
									callback : function(o, s, r) {
										var resp = Ext.decode(r.responseText);
										if (resp.success) {
											codeData = resp.rows;
										}
									}
								});
						}
						if (this.codeMap == null) {
							this.codeMap = new Map();
							var map = new Map();
							var len = codeData.length;
							for (var k = 0; k < len; k++) {
								map.put(codeData[k].itemValue.toString(),
										codeData[k].itemText);
							}
							this.codeMap.put(result[i].attributes, map);
						} else {
							var map = new Map();
							var len = codeData.length;
							for (var k = 0; k < len; k++) {
								map.put(codeData[k].itemValue.toString(),
										codeData[k].itemText);
							}
							this.codeMap.put(result[i].name, map);
						}
						break;
					default :
						break;
				}

				rs.push({
							name : result[i].name,
							type : result[i].type
						});
				if (result[i].hidden || result[i].header == '') {
					continue;
				} else {
					// 默认为空则全部加入，如果指定了字段则加入，否则不加入
					if (this.specialFields.length == 0
							|| this.specialFields.indexOf(result[i].name) != -1) {
						cms.push({
							name : result[i].name,
							tooltip : result[i].header,
							text : result[i].header,
							dataIndex : result[i].name,
							type : result[i].type,
							sortable : result[i].sortable,
							flex : result[i].fixed,
							width : result[i].width,
							hidden : result[i].hidden || result[i].header == '',
							align : result[i].align,
							sortByField : result[i].sortByField,
							attributes : result[i].attributes,
							renderer : function(value, metaData, record) {
								switch (metaData.column.type) {
									case "date" :
										// 时间格式比较另类，不能直接通过value获取对应的值，所以使用下面的方法获取
										var varDate = new Date(record.raw[metaData.column.dataIndex]);
										if (record.raw[metaData.column.dataIndex])
											return Ext.util.Format.date(
													varDate,
													metaData.column.attributes);
										else
											return "";
										break;
									case "code" :
										// metaData.column.attributes获取对应的codeName
										// 获取对应的值
										var codeList = this.codeMap
												.get(metaData.column.attributes);
										if (codeList) {
											//考虑到多选形式所以使用循环来获取数据
											var returnValue = "";
											var str = value.toString().split(",");
											for (i = 0,len=str.length; i < len; i++) {
												returnValue += codeList
														.get(str[i])
														+ ",";
											}
											if(returnValue.length>0)
											returnValue=returnValue.substring(0,returnValue.length-1);
											return returnValue;
										} else
											return "";
										break;
									default :
										return value;
										break;
								}
							}
						});
					}
				}
			}
			Ext.define('MyData' + this.gridId, {
						extend : 'Ext.data.Model',
						fields : rs,
						idProperty : this.jsonId || 'id'
					});
			this.colModel = cms;

		}
	},
	getDataStore : function() {
		var datastore = new Ext.data.Store({
					model : 'MyData' + this.gridId,
					autoLoad : false,
					pageSize : this.pageSize,
					remoteSort : this.remoteSort,
					proxy : {
						type : 'ajax',
						url : this.queryUrl,
						getMethod : function() {
							return 'POST';
						},// 亮点，设置请求方式,默认为GET
						reader : new Ext.data.reader.Json({
									root : 'rows',
									totalProperty : 'totalCount',
									id : this.jsonId || 'id'
								})
					}
				});
		return datastore;
	},
	load : function() {
		this.executeQuery();
	},
	/**
	 * 快速查询，需传递主键名和主键的值
	 */
	executeQueryBy : function(keyField, keyValue) {
		var p = new Object();
		p[keyField] = keyValue;
		// extjs4.0以上用this.store.proxy.extraParams
		this.store.proxy.extraParams = p;
		if (this.hasBbar) {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this,
						params : {
							start : 0,
							limit : this.pageSize
						}
					});
		} else {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this
					});
		}
	},
	queryByBaseParams : function(baseParams) {
		// extjs4.0以上用this.store.proxy.extraParams
		this.store.proxy.extraParams = baseParams;
		if (this.hasBbar) {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this,
						params : {
							start : 0,
							limit : this.pageSize
						}
					});
		} else {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this
					});
		}
	},
	executeQuery : function() {
		var p = new Object();
		var qf = this.searchFlds;
		for (var i = 0, len = qf.keys.length; i < len; i++) {
			var fld = qf.items[i];
			if (fld.getXType() == 'datefield' || fld.getXType() == 'combo') {
				p[qf.keys[i]] = fld.getRawValue();
			} else {
				p[qf.keys[i]] = fld.getValue();
			}

		}
		// extjs4.0以上用this.store.proxy.extraParams
		this.store.proxy.extraParams = p;
		if (this.hasBbar) {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this,
						params : {
							start : 0,
							limit : this.pageSize
						}
					});
		} else {
			this.store.load({
						callback : this.afterExecuteQuery,
						scope : this
					});
		}
	},
	afterExecuteQuery : function(r, options, success) {
		if (success) {
			// if (this.autoSelectFirstRow && this.store.getCount() > 0) {
			// this.getSelectionModel().selectFirstRow();
			// this.getView().focusRow(0);
			// }
		}
	},
	goToPrevRecord : function() {
		if (this.getStore().getCount() == 1) {
			this.reSelectCurrent();
		} else {
			this.getSelectionModel().selectPrevious(false);
		}

	},
	goToNextRecord : function() {
		if (this.getStore().getCount() == 1) {
			this.reSelectCurrent();
		} else {
			this.getSelectionModel().selectNext(false);
		}

	},
	reSelectCurrent : function() {
		var crt = this.getSelectionModel().getSelection();
		this.getSelectionModel().clearSelections();
		this.getSelectionModel().setLastFocused([crt]);
	},
	reloadRecords : function() {
		this.getStore().removeAll();
		this.getStore().reload();
	},
	deleteRecord : function() {
		if (this.getSelectionModel().getCount() < 1) {
			Ext.Msg.show({
						title : '',
						msg : '没有选择数据，无法删除。',
						buttons : Ext.Msg.OK,
						fn : this.execute_delete,
						icon : Ext.MessageBox.WARNING
					});
		} else {
			Ext.Msg.show({
						title : '删除确认',
						msg : '真的要删除这条数据吗?',
						buttons : Ext.Msg.YESNO,
						fn : this.execute_delete,
						scope : this,
						icon : Ext.MessageBox.QUESTION
					});
		}
	},
	execute_delete : function(btn) {
		if (btn == 'yes') {
			if (this.deleteUrl == null || this.deleteUrl == '') {
				return;
			}
			var selected = this.getSelectionModel().getSelection();
			// 循环删除所选数据
			// 记录用ajax已经删除的数据数量
			var deleteCount = 0;
			for (var k = 0,len=selected.length; k < len; k++) {
				var pk = new Object();
				for (var i = 0,len1=this.recordPk.length; i <len1 ; i++) {
					pk[this.recordPk[i]] = selected[k].get(this.recordPk[i]);
				}
				Ext.Ajax.request({
							url : this.deleteUrl,
							success : function(response, options) {
								// 最后一条数据的时候刷新页面
								deleteCount++;
								if (deleteCount == selected.length) {
									var resp = Ext
											.decode(response.responseText);
									if (resp.success) {
										this.executeQuery();
									} else {
										if (resp.message) {
											Ext.Msg.alert('错误', resp.message);
										} else {
											Ext.Msg.alert('错误', '删除时服务器端发生错误！');
										}
									}
								}

							},
							scope : this,
							params : pk
						});
			}

		}
	},
	after_execute_delete_success : function(response, options) {
		var resp = Ext.decode(response.responseText);
		if (resp.success) {
			var removed = this.getSelectionModel().getSelection();
			this.getStore().find('id', options.params.id);
			// this.getStore().remove(removed);
			// this.getStore().commitChanges();
		} else {
			if (resp.message) {
				Ext.Msg.alert('错误', resp.message);
			} else {
				Ext.Msg.alert('错误', '删除时服务器端发生错误！');
			}
		}
	},
	// 用于打印,生成HTML文档
	exportHtml : function() {
		this.exportList("html");
	},
	// 导出到Excle文档
	exportExcel : function() {
		this.exportList("xls");
	},
	exportList : function(p_format) {

		// 过滤条件
		var qs = '';
		var qf = this.searchFlds;
		for (var i = 0, len = qf.keys.length; i < len; i++) {
			if (qf.items[i].getValue() != undefined)
				qs = qs + '&' + qf.keys[i] + '=' + qf.items[i].getValue();
		}

		// 当前显示的字段
		var cs = '&fieldsList=';
		var f = [];
		for (var i = 0,len=this.getColumnModel().getColumnCount(); i <len ; i++) {
			if (!this.getColumnModel().isHidden(i)) {
				f.push(this.getColumnModel().getDataIndex(i));
			}
		}
		cs = cs + '' + f.join('-');

		// 当前排序字段以及排序顺序(asc,desc)
		var ss = ''; // 此处仅考虑排序，不涉及分组的问题
		if (this.getStore().getSortState()) {
			ss = '&sort=' + this.getStore().getSortState().field + '&dir='
					+ this.getStore().getSortState().direction;
		}

		var v = window
				.open(	this.queryUrl + "?export=y&_p_exp_format="
								+ ((p_format) ? p_format : "xls") + qs + cs
								+ ss, 'Export',
						'adress=no,width=710,height=450,scrollbars=yes,resizable=yes,menubar=yes');
		v.focus();
	}
});

// Ext.define('Divo.Base.GridView', Divo.Base.GridView);
